package jmine.tec.security.josso.gateway.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.josso.Lookup;
import org.josso.gateway.SSOGateway;
import org.josso.gateway.signon.Constants;

/**
 * Configura o SSO baseado no context param josso:gateway-config. Por default, usa o arquivo josso-gateway-config.xml
 * 
 * @author takeshi
 */
public class ConfigurableSSOContextListener implements ServletContextListener, Constants {

    private static final Log LOGGER = LogFactory.getLog(ConfigurableSSOContextListener.class);

    /**
     * {@inheritDoc}
     */
    public void contextInitialized(ServletContextEvent event) {
        try {
            // This will initialize all needed components
            String config = event.getServletContext().getInitParameter("josso:gateway-config");
            if (config == null) {
                config = "josso-gateway-config.xml";
            }
            Lookup lookup = Lookup.getInstance();
            lookup.init(config);
            lookup.lookupSSOGateway();

            // Build and initialize the SSO Gateway
            ServletContext ctx = event.getServletContext();
            SSOGateway g = (SSOGateway) ctx.getAttribute(KEY_JOSSO_GATEWAY);
            if (g == null) {
                g = Lookup.getInstance().lookupSSOGateway();
                ctx.setAttribute(KEY_JOSSO_GATEWAY, g);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void contextDestroyed(ServletContextEvent event) {
        SSOGateway g = (SSOGateway) event.getServletContext().getAttribute(KEY_JOSSO_GATEWAY);
        if (g != null) {
            g.destroy();
        }
    }
}
